from google.appengine.ext import webapp, db
from google.appengine.api.datastore_errors import BadKeyError
from app.helpers.queries import Query
from app.helpers.views import renders_template
from app.helpers.access import requires_permission
from app.models import ValueSet
from app.models import ValueSetInterface as Interface
from app.models.fieldsets import FieldSet, DEFAULT_PRIMARY_FIELDSET
import logging

class PeopleFind(webapp.RequestHandler):
  """ Find an individual """
  @requires_permission('find_one')
  @renders_template('people','templates','find_one.html')
  def get(self):
    return {}
  
  @requires_permission('find_one')
  @renders_template('people','templates','find_one.html')
  def post(self):
    lookups = self.request.get('lookups')
    if not lookups:
      self.response.out.write('No values entered')
      return
    lookups = lookups.split(',')
    
    interface = Interface(self.user, self.dataset)
    results = interface.lookup_primary(*lookups)
        
    return {
      'results' : results
    }

class PeopleValueset(webapp.RequestHandler):
  """ View / edit / make new value sets for an individual """
  @requires_permission('find_one')
  @renders_template('people','templates','valueset.html')
  def get(self):
    fieldsets = {}
    for fieldset in Query(FieldSet).filter(dataset_key=self.dataset.key()):
      fieldsets[fieldset.key()] = fieldset
        
    secondary_valuesets = []
    primary_valueset = None
    
    key = self.request.get('primary_key')
    if key:
      try:
        key = db.Key(key)
      except BadKeyError:
        return self.does_not_exist()
      
      for valueset in Query(ValueSet).filter(primary_key=key):
        fieldset = fieldsets.pop(valueset.fieldset_key, None)
        if not fieldset:
          logging.warning('Primary key %s has > 1 valuesets with fieldset %s' %
            (key, valueset.fieldset_key))
          continue
        
        valueset = fieldset.model.from_valueset(valueset)
        
        if valueset.is_primary:
          if primary_valueset:
            logging.warning('Two primary fieldsets for key %s' % key)
          else:
            primary_valueset = valueset
        else:
          secondary_valuesets.append(valueset)
          
      if not primary_valueset:
        return self.does_not_exist()

    else:
      primary_valueset = DEFAULT_PRIMARY_FIELDSET.model()
      fieldsets.pop(DEFAULT_PRIMARY_FIELDSET.key(), '')
    
    for fieldset in fieldsets.values():
      secondary_valuesets.append(fieldset.model())
    
    valuesets = secondary_valuesets
    valuesets.insert(0, primary_valueset)
      
    return {
      'valuesets' : valuesets,
      'primary_key' : key
    }
  
  def does_not_exist(self):
    self.response.out.write('That person does not exist')
  
  @requires_permission('find_one')
  @renders_template('people','templates','valueset.html')
  def post(self):
    key = self.request.get('key', None)
    if key:
      msg = 'Updated+existing+record'
    else:
      msg = 'Saved+new+record'
    
    valuesets = {}
    interface = Interface(self.user, self.dataset)
    first = None
    
    for name,value in self.request.params.items():
      if not value.strip():
        continue
      if '#' in name:
        name = name.split('#')
        if len(name) == 2:
          fieldset_key = name[0]
          name = name[1]
          if not first:
            first = fieldset_key
          valueset = valuesets.setdefault(fieldset_key, {})
          valueset[name] = value
    
    if first: # Move possible primary valueset to front
      items = [(first, valuesets.pop(first))] + valuesets.items()
    else:
      items = valuesets.items()
          
    interface.update_by_primary_key(key, *items)
    interface.commit()
    self.redirect('/people/valueset?flash=%s'%msg)
    return
